import pymysql
import traceback
from elasticsearch import Elasticsearch


def get_db_data(table_name):

    db = pymysql.connect(host='127.0.0.1',port=3306,  user="root", password="321",
                         database="p8_zuowu", charset="utf8")

    curses = db.cursor()
    sql = "SELECT * FROM {}".format(table_name)
    # 使用execute（）方法执行SQL查询
    curses.execute(sql)
    # 获取所有记录列表
    results = curses.fetchall()
    print("results>>>>>>>>>>", results)
    # 关闭数据库连接
    db.close()
    return results


def insert_data_to_es(table_name):
    es = Elasticsearch(hosts="http://192.144.236.210:9200/")
    rest = get_db_data(table_name)
    # 清空数据
    if es.indices.exists(index=table_name):
        es.indices.delete(index=table_name)
    try:
        i = -1
        for row in rest:
            print("111111111111111111", row)
            i += 1
            es.index(index=table_name, body={
                'id': i,
                "data": table_name,
                'img': row[4],
                'course_introduce': row[5],
                'learner': row[6],
            })
    except Exception as e:
        print(e)
        error = traceback.format_exc()
        print("Error: unable to fecth data", error)


if __name__ == '__main__':
    insert_data_to_es('tb_course')

